package com.doubao.auth.client;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Hex;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.HttpHeaders;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.methods.RequestBuilder;
import org.apache.http.client.utils.URLEncodedUtils;
import org.apache.http.conn.ssl.DefaultHostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.*;

@Slf4j
@Data
@Component
@ConfigurationProperties(prefix = "sms.huawei")
public class HuaweiCloudSmsClient {

    private String appKey;
    private String appSecret;
    private String url = "https://smsapi.cn-north-4.myhuaweicloud.com:443/sms/batchSendSms/v1";
    private String sender;
    private String templateId;
    private String signature;

    //无需修改,用于格式化鉴权头域,给"X-WSSE"参数赋值
    private static final String WSSE_HEADER_FORMAT = "UsernameToken Username=\"%s\",PasswordDigest=\"%s\",Nonce=\"%s\",Created=\"%s\"";
    //无需修改,用于格式化鉴权头域,给"Authorization"参数赋值
    private static final String AUTH_HEADER_VALUE = "WSSE realm=\"SDP\",profile=\"UsernameToken\",type=\"Appkey\"";

    /**
     * 发送短信验证码
     * @param phoneNumber 接收验证码的手机号
     * @param code 验证码
     * @return 是否发送成功
     */
    public boolean sendVerificationCode(String phoneNumber, String code) {
        try {
            // 处理手机号格式，确保符合华为云要求
            // 如果手机号不以+开头，默认添加+86
            String receiver = phoneNumber;
            if (!receiver.startsWith("+")) {
                receiver = "+86" + receiver;
            }

            // 构建模板参数，验证码作为变量参数传入模板
            String templateParas = "[\"" + code + "\"]";

            // 构建请求Body
            String statusCallbackUrl = ""; // 不设置回调地址
            String body = buildRequestBody(sender, receiver, templateId, templateParas, statusCallbackUrl, signature);
            if (body == null || body.isEmpty()) {
                log.error("构建请求Body失败");
                return false;
            }

            // 构建请求Headers
            String wsseHeader = buildWsseHeader(appKey, appSecret);
            if (wsseHeader == null || wsseHeader.isEmpty()) {
                log.error("构建WSSE Header失败");
                return false;
            }

            // 发送请求
            CloseableHttpClient client = HttpClients.custom()
                    .setSSLContext(new SSLContextBuilder().loadTrustMaterial(null,
                            (x509CertChain, authType) -> true).build())
                    .setSSLHostnameVerifier(new DefaultHostnameVerifier())
                    .build();

            HttpResponse response = client.execute(RequestBuilder.create("POST")
                    .setUri(url)
                    .addHeader(HttpHeaders.CONTENT_TYPE, "application/x-www-form-urlencoded")
                    .addHeader(HttpHeaders.AUTHORIZATION, AUTH_HEADER_VALUE)
                    .addHeader("X-WSSE", wsseHeader)
                    .setEntity(new StringEntity(body)).build());

            // 解析响应
            String responseBody = EntityUtils.toString(response.getEntity());
            log.info("华为云短信发送响应: {}", responseBody);

            // 检查发送结果
            return responseBody.contains("\"code\":\"000000\"");
        } catch (Exception e) {
            log.error("发送华为云短信验证码异常", e);
            return false;
        }
    }

    /**
     * 构造请求Body体
     */
    private String buildRequestBody(String sender, String receiver, String templateId, String templateParas,
                                    String statusCallbackUrl, String signature) {
        if (sender == null || receiver == null || templateId == null ||
                sender.isEmpty() || receiver.isEmpty() || templateId.isEmpty()) {
            log.error("buildRequestBody(): sender, receiver or templateId is null.");
            return null;
        }

        List<NameValuePair> keyValues = new ArrayList<>();

        keyValues.add(new BasicNameValuePair("from", sender));
        keyValues.add(new BasicNameValuePair("to", receiver));
        keyValues.add(new BasicNameValuePair("templateId", templateId));

        if (templateParas != null && !templateParas.isEmpty()) {
            keyValues.add(new BasicNameValuePair("templateParas", templateParas));
        }

        if (statusCallbackUrl != null && !statusCallbackUrl.isEmpty()) {
            keyValues.add(new BasicNameValuePair("statusCallback", statusCallbackUrl));
        }

        if (signature != null && !signature.isEmpty()) {
            keyValues.add(new BasicNameValuePair("signature", signature));
        }

        return URLEncodedUtils.format(keyValues, Charset.forName("UTF-8"));
    }

    /**
     * 构造X-WSSE参数值
     */
    private String buildWsseHeader(String appKey, String appSecret) {
        if (appKey == null || appSecret == null || appKey.isEmpty() || appSecret.isEmpty()) {
            log.error("buildWsseHeader(): appKey or appSecret is null.");
            return null;
        }

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
        String time = sdf.format(new Date()); // Created
        String nonce = UUID.randomUUID().toString().replace("-", ""); // Nonce

        byte[] passwordDigest = DigestUtils.sha256(nonce + time + appSecret);
        String hexDigest = Hex.encodeHexString(passwordDigest);

        // 使用JDK 1.8原生Base64类
        String passwordDigestBase64Str = Base64.encodeBase64String(hexDigest.getBytes()); // PasswordDigest

        // 若passwordDigestBase64Str中包含换行符,进行修正
        passwordDigestBase64Str = passwordDigestBase64Str.replaceAll("[\\s*\t\n\r]", "");

        return String.format(WSSE_HEADER_FORMAT, appKey, passwordDigestBase64Str, nonce, time);
    }
}